using System;
using System.Collections.Generic;
using UnityEngine;

namespace FormicArch.MVVM.Managers
{
    public class ViewModelManager : IManager
    {
        private static ViewModelManager _instance;
        public static ViewModelManager Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new ViewModelManager();
                }
                return _instance;
            }
        }

        private readonly Dictionary<Type, object> _viewModels = new Dictionary<Type, object>();
        private bool _isInitialized;

        private ViewModelManager() { }

        public void Initialize()
        {
            if (_isInitialized) return;
            _isInitialized = true;
        }

        public void Update()
        {
            // 更新所有 ViewModel
            foreach (var viewModel in _viewModels.Values)
            {
                if (viewModel is IUpdata updatable)
                {
                    updatable.Update();
                }
            }
        }

        public void OnDestroy()
        {
            foreach (var viewModel in _viewModels.Values)
            {
                if (viewModel is IDisposable disposable)
                {
                    disposable.Dispose();
                }
            }
            _viewModels.Clear();
            _isInitialized = false;
        }

        public void Dispose()
        {
            OnDestroy();
        }

        public T GetViewModel<T>() where T : class, new()
        {
            var type = typeof(T);
            if (!_viewModels.ContainsKey(type))
            {
                _viewModels[type] = new T();
            }
            return _viewModels[type] as T;
        }

        public void RegisterViewModel<T>(T viewModel) where T : class
        {
            var type = typeof(T);
            if (_viewModels.ContainsKey(type))
            {
                Debug.LogWarning($"ViewModel of type {type.Name} already exists. Overwriting...");
            }
            _viewModels[type] = viewModel;
        }

        public void UnregisterViewModel<T>() where T : class
        {
            var type = typeof(T);
            if (_viewModels.ContainsKey(type))
            {
                if (_viewModels[type] is IDisposable disposable)
                {
                    disposable.Dispose();
                }
                _viewModels.Remove(type);
            }
        }

        public bool HasViewModel<T>() where T : class
        {
            return _viewModels.ContainsKey(typeof(T));
        }
    }
}